<!-- 个税 -->
<template>
  <div class="page">
    <el-row :gutter="16" type="flex" class="row-bg">
      <el-col :span="20">
        <normal-form
          ref="updateFormRef"
          :formState="formState"
          :gridBoot="{ lg: 8, md: 12, sm: 24 }"
          :formAttrs="{
            labelWidth: '80px',
            labelPosition: 'right',
            size: 'small',
          }"
          class="normal-form"
          :rules="rules"
        >
          <template #formItem="{ formData, gridBoot }">
            <el-col v-bind="gridBoot">
              <el-form-item label="五险金额:" prop="insurances">
                <el-input
                  v-model.trim.number="formData.insurances"
                  maxlength="20"
                  placeholder="请输入每月五险扣除金额"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col v-bind="gridBoot">
              <el-form-item label="公积金额:" prop="fund">
                <el-input
                  v-model.trim.number="formData.fund"
                  maxlength="20"
                  placeholder="请输入每月公积金扣除金额"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col v-bind="gridBoot">
              <el-form-item label="专项扣除:" prop="special">
                <el-input
                  v-model.trim.number="formData.special"
                  maxlength="20"
                  placeholder="请输入每月专项扣除金额(不含免征)"
                ></el-input>
              </el-form-item>
            </el-col>
            <div
              class="base-gourp"
              v-for="(item, index) in formData.gourp"
              :key="index"
            >
              <el-col v-bind="gridBoot">
                <el-form-item
                  label="税前工资:"
                  :prop="'gourp[' + index + '].base'"
                >
                  <el-input
                    v-model.trim.number="item.base"
                    maxlength="20"
                    placeholder="请输入税前工资"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col v-bind="gridBoot">
                <el-form-item
                  label="开始月份:"
                  :prop="'gourp[' + index + '].startMonth'"
                >
                  <el-date-picker
                    v-model="item.startMonth"
                    type="month"
                    format="yyyy-MM"
                    value-format="M"
                    placeholder="请选择开始月份"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col v-bind="gridBoot">
                <el-form-item
                  label="结束月份:"
                  :prop="'gourp[' + index + '].endMonth'"
                >
                  <el-date-picker
                    v-model="item.endMonth"
                    type="month"
                    format="yyyy-MM"
                    value-format="M"
                    placeholder="请选择结束月份"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col v-bind="gridBoot">
                <div class="gourp-btns">
                  <el-button
                    v-if="index === 0"
                    type="primary"
                    icon="el-icon-plus"
                    @click="addGourp"
                    circle
                  ></el-button>
                  <el-button
                    v-if="index > 0"
                    type="warning"
                    icon="el-icon-minus"
                    @click="deleteGourp(index)"
                    circle
                  ></el-button>
                </div>
              </el-col>
            </div>
          </template>
        </normal-form>
      </el-col>
      <el-col :span="4">
        <div class="head-btns">
          <el-button type="primary" @click="handleCount">计算</el-button>
          <el-button @click="handleReset">重置</el-button>
        </div>
      </el-col>
    </el-row>
    <normal-table :context="context"></normal-table>
  </div>
</template>

<script>
import NormalForm from "@/components/template/NormalForm.vue";
import NormalTable from "@/components/template/NormalTable.vue";
export default {
  name: "IncomeTax",
  components: { NormalForm, NormalTable },
  data() {
    return {
      formState: {
        insurances: 684.6,
        fund: 181,
        special: 1000,
        gourp: [
          {
            base: 10000,
            startMonth: "1",
            endMonth: "1",
          },
        ],
      },
      rules: {},
      context: {
        loading: false,
        rowKey: "index",
        dataSource: [],
        columns: [
          {
            prop: "month",
            label: "月份",
          },
          {
            prop: "base",
            label: "税前工资",
          },
          {
            prop: "insurances",
            label: "五险",
          },
          {
            prop: "fund",
            label: "公积金",
          },
          {
            prop: "special",
            label: "专项扣除",
          },
          {
            prop: "exemption",
            label: "免征额度",
          },
          {
            prop: "tax",
            label: "个税扣除",
          },
          {
            prop: "attarTax",
            label: "税后收入",
          },
        ],
        isAction: true,
      },
    };
  },
  methods: {
    // 1. 添加一组
    addGourp() {
      this.formState.gourp.push({
        base: "",
        startMonth: "",
        endMonth: "",
      });
    },

    // 2. 删除一组
    deleteGourp(index) {
      this.formState.gourp.splice(index, 1);
    },

    // 3. 计算每月扣除费用
    countMonthlyDeduct(exemption = 5000) {
      return (
        this.formState.insurances +
        this.formState.fund +
        this.formState.special +
        exemption
      );
    },

    // 4. 计算工资总额
    countTotalWages(cd) {
      return this.formState.gourp.reduce((pre, cur) => {
        let month =
          !!cur.endMonth && cur.startMonth
            ? Number(cur.endMonth) - Number(cur.startMonth) + 1
            : 0;
        pre += cd ? cd(cur.base, month) : month * cur.base;
        return pre;
      }, 0);
    },

    // 5. 需要缴税的总工资金额(去掉需要扣除的)
    countPayableTaxTotalWages() {
      let totalMonth = 0;
      this.countTotalWages((base, month) => {
        totalMonth += month;
      });
      return this.countTotalWages() - this.countMonthlyDeduct() * totalMonth;
    },

    // 6. 需要扣除的个税总金额
    countPayableTotalTax(money) {
      let totalTax = 0;
      let taxMap = {
        36000: 36000 * 0.03,
        144000: 36000 * 0.03 + (144000 - 36000) * 0.1,
      };

      if (0 < money && money <= 36000) {
        totalTax = money * 0.03;
      } else if (36000 < money && money <= 144000) {
        totalTax = taxMap["36000"] + (money - 36000) * 0.1;
      } else if (144000 < money && money <= 300000) {
        totalTax = taxMap["144000"] + (money - 144000) * 0.2;
      }
      return totalTax;
    },

    // 7. 计算总五险一金
    countInsurancesFund() {
      let totalMonth = 0;
      this.countTotalWages((base, month) => {
        totalMonth += month;
      });
      return (this.formState.insurances + this.formState.fund) * totalMonth;
    },

    // 7. 计算税后工资总额
    countAtterTaxTotalWages() {
      return (
        this.countTotalWages() -
        this.countPayableTotalTax(this.countPayableTaxTotalWages()) -
        this.countInsurancesFund()
      );
    },

    // 8. 计算月份个税
    handleMonthTax(preTotal, monthMonry) {
      let preMonthTax = this.countPayableTotalTax(preTotal);
      let curMonthTax = this.countPayableTotalTax(preTotal + monthMonry);
      return curMonthTax - preMonthTax;
    },

    // 9. 计算月份税后
    handleMonthAtterWages(base, add) {
      return base - add - (this.formState.insurances + this.formState.fund);
    },

    // 10. 生成表格数据
    generateTable() {
      let sourceData = [];
      let preTotalMoney = 0;
      this.formState.gourp.forEach((item) => {
        let totalMonth =
          !!item.endMonth && item.startMonth
            ? Number(item.endMonth) - Number(item.startMonth) + 1
            : 0;
        for (let month = 0; month < totalMonth; month++) {
          let curMonthShouldTaxMoney = item.base - this.countMonthlyDeduct();
          let curTax = this.handleMonthTax(
            preTotalMoney,
            curMonthShouldTaxMoney
          ).toFixed(2);
          sourceData.push({
            month: Number(item.startMonth) + month,
            base: item.base,
            insurances: this.formState.insurances,
            fund: this.formState.fund,
            special: this.formState.special,
            exemption: 5000,
            tax: curTax,
            attarTax: this.handleMonthAtterWages(item.base, curTax).toFixed(2),
            // this.countAtterTaxTotalWages().toFixed(2)
          });
          preTotalMoney += curMonthShouldTaxMoney;
        }
      });
      this.context.dataSource = sourceData;
    },

    // 计算
    handleCount() {
      this.generateTable();
    },

    handleReset() {
      this.context.dataSource = [];
      this.formState= {
        insurances: undefined,
        fund: undefined,
        special: undefined,
        gourp: [
          {
            base: undefined,
            startMonth: "",
            endMonth: "",
          },
        ],
      };
    },
  },
  created() {},
  mounted() {},
};
</script>
<style lang="less" scoped>
.page {
  background: #fff;
  overflow: hidden;
  padding: 20px;
  .head-btns {
    display: flex;
  }
  .base-gourp {
    width: 100%;
    position: relative;
    .gourp-btns {
      display: flex;
      position: absolute;
      top: 2px;
      right: -37px;
    }
    .el-date-editor.el-input {
      width: 100%;
    }
  }
}
</style>
